/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gui.observer;

import gui.TalkPane;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.ConversationService;
import net.message.*;

/**
 *
 * @author Paweł
 */
public class ConversationObserver implements Observer {
    private TalkPane talkPane;

    public ConversationObserver(TalkPane talkPane) {
        this.talkPane = talkPane;
    }

    @Override
    public void update(Observable o, final Object arg) {
        if (arg instanceof MessageMessage) {
           talkPane.write(((MessageMessage) arg).getMessage());
        }
        if (arg instanceof ErrorMessage) {
            talkPane.write(((ErrorMessage) arg).getMessage());
        }
        if (arg instanceof ByeMessage) {
            try {
                ((ConversationService) o).closeConnection();
                ((javax.swing.JTabbedPane) talkPane.getParent()).remove(talkPane);
            } catch (IOException ex) {
                Logger.getLogger(ConversationObserver.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (arg instanceof HelloMessage) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    ((javax.swing.JTabbedPane) talkPane.getParent()).setTitleAt(
                        talkPane.getIndex(),
                        ((HelloMessage) arg).getMessage()
                     );
                }
            });
            
        }
    }

}
